from flask import Blueprint,request,jsonify
# 密码加密
from werkzeug.security import generate_password_hash,check_password_hash
from conf.comm import sqlalchemy_context
from database import *
import json
import re
import random
from utils.comm import send_message
from utils.redisconn import r , RedisCon

#蓝图初始化
bp_users = Blueprint('users',__name__)
#注册功能实现
@bp_users.route('/reg',methods=['POST'])
@sqlalchemy_context()

def reg():
    #获取用户输入
    data = request.data
    if not data:
        data = request.form
    else:
        data = json.loads(data)
    # 有效性验证
    ret = re.match("^1[3-9]\d{9}$",data['mobile'])
    if not ret:
        return jsonify({'code':10012,'mes':'手机号有误'})

    #构造user
    try:
         user = User(username=data['username'],password=generate_password_hash(data['password']),mobile=data['mobile'])
         db.session.add(user)
         db.session.commit()
         return jsonify({"code":200})
    except:
        return jsonify({"code":10010})


@bp_users.route('/sendsms',methods=['POST'])
def sendsms():
    #传递手机号
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    mobile = data['mobile']
    #有效性验证，正则验证手机号
    reg = re.match('^1[3-9]\d{9}$',data['mobile'])
    if not reg:
        return jsonify({'code':10012,'mes':'必须输入手机号'})
    #生成验证码    
    code = str(random.randint(100000,999999))
    #调用短信接口
    flag = send_message(mobile,code,1)
    if flag:
        #发送成功，存入redis
        r.set_str(mobile,code,60)
        #返回结果（验证码）
        return jsonify({'code':200,'smscode':code})
    else:
        return jsonify({'code':20011,'mes':'发送失败，请重试'})

@bp_users.route('/login/',methods=['POST'])
def login():
     #用户名登录
    username = request.args.get('username')
    password = request.args.get('password')
    mobile = request.args.get('mobile')
    code = request.args.get('code')
    # print(username,password)
    # return 'ok'
    if username:
        #查询这个用户信息 
        user = User.query.filter_by(username=username).first()
        if user:
            if check_password_hash(user.password,password):
                return jsonify({'code':200,'msg':'登录成功','userid':user.id,'username':user.username})
            else:
                return jsonify({'code':20030,'msg':'用户名或密码错误'}) 
        else:
            return jsonify({'code':20020,'msg':'该用户不存在'})

    if mobile:    
        #手机号登录
        #获取前端验证码
        #获取后台验证码
        r=RedisCon()
        hcode = r.get_str(mobile)  #得到的是b开头的二进制数据
        print(hcode)
        if hcode:
            if int(code) == int(hcode):
                #写到数据库
                user = User.query.filter_by(mobile=mobile).first()
                if not user:
                    user = User(mobile=mobile,username=mobile)
                    db.session.add(user)
                    db.session.commit()
                r.del_str(mobile)
                return jsonify({'code':200,'msg':'登录成功','userid':user.id,'username':user.username})
            else:
                return jsonify({'code':20050,'msg':'验证码输入错误，请重新输入'})
        else:
            return jsonify({'code':20040,'msg':'验证码不存在'})